<template>
  <div class="club-detail">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">俱乐部详情</span>
      </template>
    </el-page-header>

    <div v-loading="loading" class="content">
      <el-row :gutter="20">
        <!-- 基本信息 -->
        <el-col :span="16">
          <el-card class="info-card">
            <template #header>
              <span class="card-title">基本信息</span>
            </template>
            
            <div class="club-header">
              <el-avatar :src="club.avatar || '/default-club.png'" :size="100" />
              <div class="header-info">
                <h2>{{ club.name }}</h2>
                <div class="meta">
                  <el-tag :type="getStatusType(club.status)">{{ getStatusText(club.status) }}</el-tag>
                  <el-tag type="success" class="ml-2">Lv.{{ club.level || 1 }}</el-tag>
                  <span class="ml-2 text-muted">积分: {{ club.points || 0 }}</span>
                </div>
              </div>
            </div>

            <el-descriptions :column="2" border class="mt-4">
              <el-descriptions-item label="俱乐部ID">{{ club.id }}</el-descriptions-item>
              <el-descriptions-item label="创建者ID">{{ club.creatorId }}</el-descriptions-item>
              <el-descriptions-item label="成员数">
                {{ club.currentMembers || 0 }} / {{ club.maxMembers || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="运动类型">{{ club.sportTypes || '暂无' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">{{ formatDate(club.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">
                {{ club.description || '暂无描述' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 成员列表 -->
          <el-card class="members-card mt-3">
            <template #header>
              <div class="card-header">
                <span class="card-title">成员列表</span>
                <el-input
                  v-model="memberSearch"
                  placeholder="搜索成员"
                  clearable
                  style="width: 200px"
                />
              </div>
            </template>

            <el-table :data="filteredMembers" stripe>
              <el-table-column prop="userId" label="用户ID" width="100" />
              <el-table-column prop="role" label="角色" width="120">
                <template #default="{ row }">
                  <el-tag :type="getMemberRoleType(row.role)">
                    {{ getMemberRoleText(row.role) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getMemberStatusType(row.status)">
                    {{ getMemberStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="eventsParticipated" label="参与活动" width="100" />
              <el-table-column prop="contributionPoints" label="贡献积分" width="100" />
              <el-table-column prop="joinedAt" label="加入时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.joinedAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button 
                    v-if="row.status === 'pending'" 
                    link 
                    type="success" 
                    size="small" 
                    @click="approveMember(row.id)"
                  >
                    通过
                  </el-button>
                  <el-button 
                    v-if="row.status === 'pending'" 
                    link 
                    type="danger" 
                    size="small" 
                    @click="rejectMember(row.id)"
                  >
                    拒绝
                  </el-button>
                  <el-button 
                    v-if="row.status === 'active' && row.role !== 'owner'" 
                    link 
                    type="danger" 
                    size="small" 
                    @click="kickMember(row.id)"
                  >
                    踢出
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 侧边栏 -->
        <el-col :span="8">
          <!-- 快速操作 -->
          <el-card v-if="club.status === 'pending'" class="action-card">
            <template #header>
              <span class="card-title">审核操作</span>
            </template>
            <el-space direction="vertical" :size="12" style="width: 100%">
              <el-button 
                type="success" 
                style="width: 100%" 
                @click="approveClub"
              >
                通过审核
              </el-button>
              <el-button 
                type="danger" 
                style="width: 100%" 
                @click="rejectClub"
              >
                拒绝审核
              </el-button>
            </el-space>
          </el-card>

          <!-- 统计信息 -->
          <el-card class="stats-card" :class="{'mt-3': club.status === 'pending'}">
            <template #header>
              <span class="card-title">统计信息</span>
            </template>
            <div class="stat-item">
              <span class="stat-label">总成员数</span>
              <span class="stat-value">{{ club.currentMembers || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">俱乐部等级</span>
              <span class="stat-value">Lv.{{ club.level || 1 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">俱乐部积分</span>
              <span class="stat-value">{{ club.points || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">待审核成员</span>
              <span class="stat-value">{{ pendingMembersCount }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { clubApi } from '@/api/club'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const club = ref({})
const members = ref([])
const memberSearch = ref('')

const clubId = computed(() => route.params.id)

const filteredMembers = computed(() => {
  if (!memberSearch.value) return members.value
  return members.value.filter(m => 
    m.userId.toString().includes(memberSearch.value)
  )
})

const pendingMembersCount = computed(() => {
  return members.value.filter(m => m.status === 'pending').length
})

onMounted(() => {
  loadClubDetail()
  loadMembers()
})

const loadClubDetail = async () => {
  loading.value = true
  try {
    club.value = await clubApi.getClubDetail(clubId.value)
  } catch (error) {
    console.error('加载俱乐部详情失败:', error)
    ElMessage.error('加载俱乐部详情失败')
  } finally {
    loading.value = false
  }
}

const loadMembers = async () => {
  try {
    members.value = await clubApi.getClubMembers(clubId.value)
  } catch (error) {
    console.error('加载成员列表失败:', error)
  }
}

const approveClub = () => {
  ElMessageBox.confirm('确定要通过该俱乐部的审核吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(async () => {
    try {
      await clubApi.approveClub(clubId.value)
      ElMessage.success('审核通过')
      loadClubDetail()
    } catch (error) {
      console.error('审核失败:', error)
    }
  }).catch(() => {})
}

const rejectClub = () => {
  ElMessageBox.prompt('请输入拒绝原因', '拒绝审核', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入拒绝原因'
  }).then(async ({ value }) => {
    try {
      await clubApi.rejectClub(clubId.value, value)
      ElMessage.success('已拒绝')
      loadClubDetail()
    } catch (error) {
      console.error('操作失败:', error)
    }
  }).catch(() => {})
}

const approveMember = async (memberId) => {
  try {
    await clubApi.approveMember(memberId, true)
    ElMessage.success('已通过')
    loadMembers()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const rejectMember = async (memberId) => {
  try {
    await clubApi.approveMember(memberId, false)
    ElMessage.success('已拒绝')
    loadMembers()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const kickMember = (memberId) => {
  ElMessageBox.confirm('确定要踢出该成员吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await clubApi.kickMember(clubId.value, memberId)
      ElMessage.success('已踢出')
      loadMembers()
    } catch (error) {
      console.error('操作失败:', error)
    }
  }).catch(() => {})
}

const goBack = () => {
  router.back()
}

const getStatusType = (status) => {
  const types = { pending: 'warning', approved: 'success', rejected: 'danger', active: 'success' }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = { pending: '待审核', approved: '已通过', rejected: '已拒绝', active: '活跃' }
  return texts[status] || status
}

const getMemberRoleType = (role) => {
  const types = { owner: 'danger', admin: 'warning', member: '' }
  return types[role] || ''
}

const getMemberRoleText = (role) => {
  const texts = { owner: '所有者', admin: '管理员', member: '成员' }
  return texts[role] || role
}

const getMemberStatusType = (status) => {
  const types = { active: 'success', pending: 'warning', rejected: 'danger', left: 'info' }
  return types[status] || ''
}

const getMemberStatusText = (status) => {
  const texts = { active: '活跃', pending: '待审核', rejected: '已拒绝', left: '已退出' }
  return texts[status] || status
}

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}
</script>

<style scoped>
.club-detail {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
}

.club-header {
  display: flex;
  gap: 20px;
  align-items: center;
}

.header-info h2 {
  margin: 0 0 12px 0;
  font-size: 24px;
}

.meta {
  display: flex;
  align-items: center;
}

.ml-2 {
  margin-left: 8px;
}

.mt-3 {
  margin-top: 16px;
}

.mt-4 {
  margin-top: 20px;
}

.text-muted {
  color: #909399;
}

.card-title {
  font-weight: 600;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: 600;
  color: #303133;
}
</style>

